//*** A TYPICAL MEMORY LEAK *** 

#include <iostream>  //N.B. no ".h": new-style include.
#include <cstring>
using namespace std; //Everything in 'std' is accessed directly.

//A simple string class.
class SimpleString {
  
public:

  explicit SimpleString(char* data = "");  //Use 'explicit' keyword to disable
                                           //automatic type conversions --
                                           //generally a good idea.

  virtual ~SimpleString();   //Virtual destructor, in case someone inherits
                             //from this class.

  virtual const char* to_cstr() const;  //Get a read-only C string.

  //Many other methods are needed to create a complete string class.
  //This example implements only a tiny subset of these, in order
  //to keep the discussion focused.

  //N.B. no 'inline' methods -- add inlining later, if needed for
  //optimization.

private:
  char* data_p_; //Distinguish private class members: a trailing underscore
                 //in the name is one common method.
  
};


//Constructor. 
SimpleString::SimpleString(char* data_p) :
  data_p_(new char[strlen(data_p)+1]) {
  strcpy(data_p_,data_p);
}

//Destructor.
SimpleString::~SimpleString() {
  //OOPS, forgot to delete "data_p".
  
  //Deleting it twice is also bad bad bad
  //delete data_p_;
  //delete data_p_;
}


//Returns a read-only C string representation.
const char* SimpleString::to_cstr() const {
  return data_p_;
}


int main() {
  //Create a local SimpleString.
  SimpleString name("O'Reilly Onlamp");

  //Print it out.
  cout << name.to_cstr() << endl;
  cout << "No error will be given but we have a leak "<< endl;

  //The lines above weere added later the main point here is that
  //the person didnt delete the membe data_p_ in the destructor

  SimpleString *name2 = new SimpleString("Denis was here");
  delete name2;
  //good habit
  name2=0;

  if (!name2)
      cout << "The name 2 was deleted man you can reuse the pointer if you need it " << endl;

  name2 = new SimpleString("Reusing the pointer");
  cout << name2->to_cstr() << endl;
  delete name2;
  name2 = 0;


}

//*** END: A TYPICAL MEMORY LEAK ***
